package models;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;

import com.sun.org.apache.bcel.internal.generic.DCMPG;

import utils.Strings;

/**
 * 字段模型
 * 
 * @author ultrafrog
 * @version 1.0, 2015-03-30
 * @since 1.0
 */
@Entity
@Table(name = "dbc_field")
public class Field extends Model {

	/** 名称 */
	@Column(name = "vc_name")
	public String name;
	
	/** 代码 */
	@Column(name = "vc_code")
	public String code;
	
	/** 类型 */
	@Column(name = "dc_type")
	public String type;
	
	/** 长度 */
	@Column(name = "nb_length")
	public Integer length;
	
	/** 精确 */
	@Column(name = "nb_precision")
	public Integer precision;
	
	/** 空允许 */
	@Column(name = "dc_nullable")
	public String nullable;
	
	/** 备注 */
	@Column(name = "vc_remark")
	public String remark;
	
	/** 顺序 */
	@Column(name = "nb_order")
	public Integer order;
	
	/** 数据表编号 */
	@Column(name = "fk_table_id")
	public String tableId;
	
	/** 字段字典列表 */
	@Transient
	public List<FieldDict> dicts;
	
	/** 构造函数 */
	public Field() {
		dicts = new ArrayList<FieldDict>();
	}
	
	/**
	 * 构造函数 
	 * 
	 * @param name
	 * @param code
	 * @param type
	 * @param length
	 * @param precision
	 * @param nullable
	 * @param remark
	 * @param order
	 * @param tableId
	 */
	public Field(String name, String code, String type, Integer length, Integer precision, String nullable, String remark, Integer order, String tableId) {
		this();
		this.name = name;
		this.code = code;
		this.type = type;
		this.length = length;
		this.precision = precision;
		this.nullable = nullable;
		this.remark = remark;
		this.order = order;
		this.tableId = tableId;
	}
	
	/**
	 * 转换成长度字符串
	 * 
	 * @return
	 */
	public String toLengthString() {
		if (length == null) return "-";
		if (precision == null) return String.valueOf(length);
		else return length + "," + precision;
	}
	
	/**
	 * 转换成备注字符串
	 * 
	 * @return
	 */
	public String toRemarkString() {
		if (Strings.empty(remark) && dicts.size() == 0) return "-";
		
		List<String> lString = new ArrayList<String>();
		if (!Strings.empty(remark)) lString.add(remark);
		for (FieldDict fd: dicts) lString.add(String.format("%s - %s", fd.value, fd.name));
		return Strings.implode(lString, "<br>");
	}
}
